package org.vectrics.web.menu;


import org.apache.log4j.Category;
import java.util.Vector;
import java.util.Iterator;

public class Menu extends MenuItem {
    private static Category log = Category.getInstance(Menu.class);
    private MenuItem selectItem = null;
    private String contextPath = null;
    private Vector selectionMap = new Vector();

    public Menu() {
    	super();
    }

    // override of MenuItem method.
    public Menu getMenu() {
        return(this);
    }
    
    public void addSelectionMapEntry(String httpPath, String selectMenuId) {
    	selectionMap.add(new SelectionMapEntry(httpPath, selectMenuId));
    }
    
    
	public MenuItem findSelectedItemForPath(String httpPath) {
		log.debug("findSelectedItemForPath() - method for finding child element which will be"
				+ " shown as selected for http path");
	
		MenuItem selectItem = null;
		SelectionMapEntry selectedEntry = null;
		
		Iterator iter = this.selectionMap.iterator();
		while ((selectItem == null) && (iter.hasNext())) {
			SelectionMapEntry entry = (SelectionMapEntry)iter.next();
			if (httpPath.indexOf(entry.getHttpPath()) >= 0) {
				if (selectedEntry == null) {
					selectedEntry = entry;
				}
				else if (selectedEntry.getHttpPath().length() < entry.getHttpPath().length()) {
					selectedEntry = entry;
				}
			}
		}
		
		if (selectedEntry != null) {
			selectItem = this.findItemWithId(selectedEntry.getMenuId());
		}
		
		if (log.isDebugEnabled()) {    
			log.debug("findSelectedItemForPath() - path = " + httpPath);
			if (selectItem == null) {
				log.debug("findSelectedItemForPath() - could not find select MenuItem for path");
			}
			else { 
				log.debug("findSelectedItemForPath() - found selected menu item: " + selectItem.getId());
			}
		}
		return(selectItem);
	}    
    
    public MenuItem getSelectedItem() {
        return(selectItem);
    }
    
    public  void setSelectedItem(MenuItem item) {
        selectItem = item;
    }
 
    public void setSelectItem(String itemId) {
        MenuItem item = findItemWithId(itemId);
        if (item == null)
            if (itemId.trim().length() > 0)
                log.error("selectItem() - could not find item with ID = " + itemId);
            else
                log.debug("selectItem() - could not find item with ID = " + itemId);
        else {
            setSelectedItem(item);
        }
    }


	/**
	 * @return
	 */
	public String getContextPath() {
		return contextPath;
	}

	/**
	 * @param contextPath
	 */
	public void setContextPath(String contextPath) {
		this.contextPath = contextPath;
	}

}